package controllers

import (
	"2301_zk3/cache"
	"2301_zk3/models"
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
)

var ctx = context.Background()

type GuangController struct {
	beego.Controller
}

func (c *GuangController) Add() {
	name := c.GetString("name")
	zhong := c.GetString("zhong")
	address := c.GetString("address")
	datetime := c.GetString("datetime")
	status := c.GetString("status")
	if name == "" || zhong == "" || address == "" || datetime == "" || status == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加参数不能为空",
		}
		c.ServeJSON()
		return
	}

	var guang models.Guang
	guang.Name = name
	guang.Zhong = zhong
	guang.Address = address
	guang.Datetime = datetime
	guang.Status = status
	err := guang.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加参数错误",
		}
		c.ServeJSON()
		return
	}
	guangs, _ := guang.List()
	jsonData, _ := json.Marshal(guangs)
	cache.Rdb.Set(ctx, "guang", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *GuangController) List() {
	cacheData := cache.Rdb.Get(ctx, "guang_list").Val()
	var guangs []models.Guang
	if cacheData != "" {
		models.DB.Find(&guangs)
		jsonData, _ := json.Marshal(guangs)
		cache.Rdb.Set(ctx, "guang_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &guangs)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "获取成功",
	}
	c.ServeJSON()
	return
}
func (c *GuangController) Del() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}
	var guang models.Guang
	guang.ID = uint(id)
	err := guang.Del()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	guangs, _ := guang.List()
	jsonData, _ := json.Marshal(guangs)
	cache.Rdb.Set(ctx, "guang", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
func (c *GuangController) Update() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}
	var guang models.Guang
	name := c.GetString("name")
	zhong := c.GetString("zhong")
	address := c.GetString("address")
	datetime := c.GetString("datetime")
	status := c.GetString("status")
	guang.ID = uint(id)
	guang.Name = name
	guang.Zhong = zhong
	guang.Address = address
	guang.Datetime = datetime
	guang.Status = status

	err := guang.Update()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "更新失败",
		}
		c.ServeJSON()
		return
	}
	guangs, _ := guang.List()
	jsonData, _ := json.Marshal(guangs)
	cache.Rdb.Set(ctx, "guang", jsonData, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "更新成功",
	}
	c.ServeJSON()
	return
}
